package cms.service.access;

import cms.bean.ErrorView;
import cms.bean.user.AccessUser;
import cms.common.data.ApiResult;
import cms.common.data.ApiResultCode;
import cms.common.exception.ServiceException;
import cms.manage.CSRFTokenManage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class CsrfTokenAccessService implements AccessService<String>{
    @Resource
    CSRFTokenManage csrfTokenManage;

    /**
     * 令牌访问
     * @param accessUser
     * @param act
     * @param request
     * @param token
     * @return
     */
    public ApiResult access(AccessUser accessUser,String act, HttpServletRequest request, String token) {
        if (token != null && !"".equals(token.trim())) {//判断令牌
            String tokenSessionid = csrfTokenManage.getToken(request);//获取令牌
            if (tokenSessionid != null && !"".equals(tokenSessionid.trim())) {
                if (!tokenSessionid.equals(token)) {
                    throw new ServiceException(ApiResultCode.PARAM_ERROR.setMessage(ErrorView._13.name()));
                    //error.put("token", ErrorView._13.name());//令牌错误
                }
            }else{
                throw new ServiceException(ApiResultCode.PARAM_ERROR.setMessage(ErrorView._12.name()));
//                error.put("token", ErrorView._12.name());//令牌过期
            }
        }else{
//            error.put("token", ErrorView._11.name());//令牌为空
            throw new ServiceException(ApiResultCode.PARAM_NULL.setMessage(ErrorView._12.name()));
        }
        return ApiResult.buildSuccess();
    }
}
